# -*- coding:utf8 -*-

from flask import render_template
from flask import request, current_app
from flask import jsonify
import hashlib
from b2c.controllers.customer import c_bp
# from . import validate_arg
# from lyra.service import UserService, AlbumService, ScoreService
# from lyra.controllers.web.validators import ShareMp3Input

from b2c.external.onenet import OneNet


@c_bp.route('/', methods=['GET', 'POST'])
def index():
    try:
        args = request.args
        signature = args.get('signature')
        timestamp = args.get('timestamp')
        nonce = args.get('nonce')
        echostr = args.get('echostr')
        token = 'zhangsheng'

        list = [token, timestamp, nonce]
        list.sort()
        sha1 = hashlib.sha1()
        map(sha1.update, list)
        hashcode = sha1.hexdigest()
        print('handle/Get func: hashcode, signature: ', hashcode, signature)
        if hashcode == signature:
            return str(echostr)
        else:
            return ''
    except Exception as e:
        print(e)
        return str(e)


@c_bp.route('/get_paper', methods=['GET'])
def get_paper():
    onenet = OneNet()
    rst = onenet.send_cmds(cmd_name='get_paper', device_id='35272885')
    if rst['errno']:
        errno = rst['errno']
        error = onenet.error_list.get(errno) or rst.get('error')
        return render_template('wechat/error.html', error=error)
    else:
        return render_template('wechat/get_paper.html')


@c_bp.route('/add_paper', methods=['GET'])
def add_paper():
    onenet = OneNet()
    rst = onenet.send_cmds(cmd_name='add_paper', device_id='35272885', paper_num=50)
    if rst['errno']:
        errno = rst['errno']
        error = onenet.error_list.get(errno) or rst.get('error')
        return render_template('wechat/error.html', error=error)
    else:
        return render_template('wechat/add_paper.html')


@c_bp.route('/open_door', methods=['GET'])
def open_door():
    onenet = OneNet()
    rst = onenet.send_cmds(cmd_name='open_door', device_id='35272885')
    if rst['errno']:
        errno = rst['errno']
        error = onenet.error_list.get(errno) or rst.get('error')
        return render_template('wechat/error.html', error=error)
    else:
        return render_template('wechat/open_door.html')


@c_bp.route('/close_door', methods=['GET'])
def close_door():
    onenet = OneNet()
    rst = onenet.send_cmds(cmd_name='close_door', device_id='35272885')
    if rst['errno']:
        return jsonify(rst)
    else:
        return jsonify('The door close success')


@c_bp.route('/show_index', methods=['GET'])
def show_index():
    return render_template('wechat/open_door.html')

